﻿/// <reference path="Meres.Administration.js" />

var loadingIcon = '#loadingIcon';
var square1 = "180px";
var gridDefs = [
{
    "ColumnDefinitions": [{ "Width": "250px" }, { "Width": "100%" }],
    "RowDefinitions": [{ "Height": "100%" }]
},
{
    "ColumnDefinitions": [{ "Width": "50%" }, { "Width": "280px" }, { "Width": "50%" }],
    "RowDefinitions": [{ "Height": "100%" }]
},

{
    "ColumnDefinitions": [{ "Width": "50%" }, { "Width": square1 }, { "Width": square1 }, { "Width": square1 }, { "Width": square1 }, { "Width": "50%" }],
    "RowDefinitions": [{ "Height": "50px" }, { "Height": square1 }, { "Height": square1 }, { "Height": square1 }, { "Height": "100%" }]
},
{
    "ColumnDefinitions": [{ "Width": "200px" }, { "Width": "100%" }],
    "RowDefinitions": [{ "Height": "100%" }]
},
{
    "ColumnDefinitions": [{ "Width": "200px" }, { "Width": "100%" }],
    "RowDefinitions": [{ "Height": "100%" }]
},
{
    "ColumnDefinitions": [{ "Width": "200px" }, { "Width": "5px" }, { "Width": "100%" }],
    "RowDefinitions": [{ "Height": "100%" }],
    "Name": "Type1_Splitter"
},
{
    "ColumnDefinitions": [{ "Width": "100%" }, { "Width": "5px" }, { "Width": "200px" }],
    "RowDefinitions": [{ "Height": "200px" }, { "Height": "5px" }, { "Height": "100%" }],
    "Name": "Type2_Splitter_Vertical"
}

];


var availableTags = [
			"ActionScript",
			"AppleScript",
			"Asp",
			"BASIC",
			"C",
			"C++",
			"Clojure",
			"COBOL",
			"ColdFusion",
			"Erlang",
			"Fortran",
			"Groovy",
			"Haskell",
			"Java",
			"JavaScript",
			"Lisp",
			"Perl",
			"PHP",
			"Python",
			"Ruby",
			"Scala",
			"Scheme"
];



$(function () {
    $('#layout-navigation').remove();


    Meres.init();
});

Meres = function () {
    var moduleList = [
        {
            "name": "Administration",
            "reqUrl": "/Meres/Administration/Index",
            "jsInstall": function () { administration(); },
            "icon": '-0px -20px'
        },
        {
            "name": "StartPage",
            "reqUrl": "/Meres/MeresMain/StartPage",
            "jsInstall": function () { installStartPage(); },
            "icon": '-62px 0px',
            "title": "Start",
            "tabPos": 0
        },
        {
            "name": "People",
            "reqUrl": "/Meres/People/Index",
            "jsInstall": function (evt) {
                var code = new people();
                code.perform(evt);
            },
            "icon": '-85px 0px'
        },
        {
            "name": "Projects",
            "reqUrl": '/Meres/Projects/Index',
            "jsInstall": function () { projects() }
        },
        {
            "name": "MyScheduler",
            "reqUrl": '/Meres/MeresMain/MyScheduler',
            "jsInstall": function () { schedulerView() },
            "icon": '-22px -20px',
            "title": "My Scheduler"
        },
        {
            "name": "RelationshipDiagram",
            "reqUrl": '/Meres/RelationshipDiagram/Index',
            "jsInstall": function () { relationshipDiagram(); },
            "icon": '-50px -20px',
            "title": "Diagrams"
        },
        {
            "name": "PointOfSale",
            "reqUrl": '/Meres/PointOfSale/Index',
            "jsInstall": function () { pointOfSale(); },
            "icon": '-50px -20px',
            "title": "Point of Sale",
            "ShowInTab": false
        },
        {
            "name": "ProcessManagement",
            "reqUrl": '/Meres/ProcessManagement/TestDetailView',
            "jsInstall": function () { ProcessManagement(); },
            "icon": '-50px -20px',
            "title": "Process Management"
        }
    ];

    this.init = function () {
        $(loadingIcon).attr('src', '/Modules/Eking.Framework/Styles/loading.gif');

        installjQueryPlugin();
        installjXamlGrid();

        //this.openModule("StartPage");
        //this.openModule("People",{"View":"Icon","Filter":"All"});
        //this.openModule("People");
        //this.openModule("MyScheduler");
        this.openModule("RelationshipDiagram");
        //this.openModule("Administration");
        //this.openModule("PointOfSale");
        //this.openModule("ProcessManagement");
    };

    // Reg UI event
    function installjXamlGrid() {
        $("#menuLayout").jXamlGrid({
            gridDef: gridDefs[1]
        });
    }

    function installStartPage() {
        // to make animation
        $('.startpageBigIcon').css('width', '180px');
        $('.startpageBigIcon').css('height', '180px');
        
        refreshjScrollPane();
    }

    function installjQueryPlugin() {
        $('#meres').resizable();

        ddsmoothmenu.shadow = { enable: false };

        ddsmoothmenu.init({
            mainmenuid: "mainMenu", //menu DIV id
            orientation: 'h', //Horizontal or vertical menu: Set to "h" or "v"
            classname: 'ddsmoothmenu', //class added to menu's outer DIV
            //customtheme: ["#1c5a80", "#18374a"],
            contentsource: "markup", //"markup" or ["container_id", "path_to_menu_file"]
            openonclick: true
        });

        ddsmoothmenu.init({
            mainmenuid: "loginMenu", //menu DIV id
            orientation: 'h', //Horizontal or vertical menu: Set to "h" or "v"
            classname: 'ddsmoothmenu', //class added to menu's outer DIV
            //customtheme: ["#1c5a80", "#18374a"],
            contentsource: "markup", //"markup" or ["container_id", "path_to_menu_file"],                        
        });

        $tabs = $("#contentPresenter").tabs({
            tabTemplate: "<li><a href='#{href}'><span class='ekingIcon moduleTabIcon'></span>#{label}</a> <span class='ui-icon ui-icon-close'>Remove Tab</span></li>",
            add: function (event, ui) {
                var span = $(ui.tab).parent('li').find('.moduleTabIcon');
                if (moduleIcon == undefined)
                    span.remove();
                else
                    span.css('background-position', moduleIcon);
            }
        });

        $("#contentPresenter").bind('tabsselect', function (event, ui) {
            //if ($(ui.panel).attr('id') == "tabs-StartPage")
            //    refreshjScrollPane();
        });

        $(".moduleTab span.ui-icon-close").live("click", function () {
            var index = $("li", $tabs).index($(this).parent());
            $tabs.tabs("remove", index);
        });

        $("#searchBox input").autocomplete({
            source: availableTags
        });

        $("#dialog-form").dialog({
            autoOpen: false,
            height: 200,
            width: 400,
            modal: true,
            buttons: {
                OK: function () {
                },
                Cancel: function () {
                    $(this).dialog("close");
                }
            }
        });
    }

    var $tabs;
    var moduleIcon = undefined;

    this.openModule = function (moduleName, evt) {
        var module = moduleList.singleOrDefault(function (item) {
            return item.name == moduleName;
        });

        if (module == undefined) {
            //throw 'Not supported Module:' + moduleName;
            setStatus({ type: 'alert', msg: 'Module "' + moduleName + '" isnot available yet' });
            return;
        }

        if (module.ShowInTab != false)
            openModuleInTab(module, evt);
        else if (module.name == "PointOfSale") {
                // Full screen
            openModuleFullScreen(module, evt);
        }
    };

    function openModuleFullScreen(module, evt) {
        doAjax(module.reqUrl, function (evt1) {
            $('#fullScreenModuleContainer').fadeIn();
            $('#fullScreenModuleContainer').addClass("hosting");
            $('#fullScreenModuleContainer').html(evt1);

            module.jsInstall(evt);
            $('.closeModule').click(function () {
                closeModuleFullScreen();
            });
            module.jsInstall(evt);
        });
    }

    function closeModuleFullScreen() {
        $('#fullScreenModuleContainer').removeClass("hosting");
        $('#fullScreenModuleContainer').html("");
    }

    function openModuleInTab(module, evt) {
        moduleIcon = undefined;
        var tab_id = "#tabs-" + module.name;
        if ($(tab_id).length != 0) {
            $tabs.tabs("select", tab_id);
            return;
        }

        moduleIcon = module.icon;

        if (module.tabPos != undefined)
            $tabs.tabs("add", tab_id, module.title == undefined ? module.name : module.title, module.tabPos);
        else
            $tabs.tabs("add", tab_id, module.title == undefined ? module.name : module.title);

        $tabs.tabs("select", tab_id);

        $tabs.find(".ui-tabs-nav").sortable({ axis: "x" });

        var moduleEvt = evt;

        doAjax(module.reqUrl, function (evt1) {
            $(tab_id).html(evt1);
            module.jsInstall(moduleEvt);
        });

    }
};

Meres = new Meres();

function refreshjScrollPane() {
    $('.jScrollPane').jScrollPane({ showArrows: true });
}

var loadingCall = 0;

function loading() {
    loadingCall++;
    $(loadingIcon).css('visibility', 'visible');
};

function unloading() {
    loadingCall--;
    if (loadingCall < 0)
        loadingCall = 0;
    if (loadingCall == 0)
        $(loadingIcon).css('visibility', 'hidden');
};

function doAjax(url, success, data, method, datatype, contentType) {
    if (method == undefined)
        method = 'GET';
    var params = {
        url: url,
        type: method,
        data: data,
        fail: function (evt) {
            unloading();
            setStatus({ type: 'error', msg: evt });
        },
        error: function (evt) {
            unloading();
            setStatus({ type: 'error', msg: evt });
        },
        success: function (evt) {
            unloading();
            success(evt);
        }
    };
    if (datatype != undefined)
        params.dataType = datatype;
    if (contentType != undefined)
        params.contentType = contentType;
    loading();
    $.ajax(params);
}

function renderActionBar(options) {
    var icons = {
        delete: "ui-icon-trash",
        add: "ui-icon-plus",
        clone: "ui-icon ui-icon-copy",
        listView: "ekingIcon-listView",
        iconView: "ekingIcon-iconView",
        detailPersonView: "ekingIcon-detailPersonView",
        detailRdView: "ekingIcon-detailRdView",
        save: "ui-icon-disk"
    };
    var $t = $(options.target);
    $t.html('');
    var commands = options.commands;
    var viewModes = options.viewModes;
    if (commands == undefined)
        commands = [];
    if (viewModes == undefined)
        viewModes = [];

    var html = '<span class="commands">';

    for (var i = 0; i < commands.length; i++) {
        var item = commands[i];
        html += '<span class="flatStyle @item" title="@item"><span class="ui-icon @icon"></span></span>'
            .replaceAll("@icon", eval('icons.' + item))
            .replaceAll("@item", item);
    }
    html += '</span>';

    html += '<ul style="float: right;" class="viewMode">';
    for (var i = 0; i < viewModes.length; i++) {
        var item = viewModes[i];
        html += '<li class="@item" title="@item"><span class="ekingIcon @icon"></span></li>'
            .replaceAll("@icon", eval('icons.' + item))
            .replaceAll("@item", item);
    }

    html += '</ul>';

    $t.html(html);

    $t.find('.viewMode').selectable({
        selected: function (event, ui) {
            if (options.viewModeSelected == undefined)
                return;
            options.viewModeSelected(event, ui);
        }
    });
}

var counter = 0;
$().ready(function () {
    $('#messageDiv').slideUp();
    $('#btnTest').hide();
    $('#btnTest').click(function () {
        //counter++;
        //var chk = counter % 4;
        //if (chk == 0)
        //    setStatus({ type: 'error', msg: 'Error updating data' });
        //else if (chk == 1)
        //    setStatus({ type: 'alert', msg: 'Warning! lost connection' });
        //else if (chk == 2)
        //    setStatus({ type: 'info', msg: 'Saved' });
        //else if (chk == 3)
        //    setStatus({});

        throw 'TEST AN ERROR';
    });

    window.onerror = function (evt) {
        setStatus({ type: 'error', msg: evt });
    };

    $('#messageDiv .closeMessage').click(function () {
        $('#messageDiv').slideUp();
    });
});


function log(text) {
    $("#alog").append(text + "<br />");
    //$("#alog").prop({ scrollTop: $("#alog").prop("scrollHeight") });

    //        var objDiv = document.getElementById("#alog");
    //        objDiv.scrollTop = objDiv.scrollHeight;
}



function setStatus(options) {
    var $msgDiv = $('#messageDiv');
    $msgDiv.slideUp();

    if (options.msg != undefined) {
        $('#messageDiv .leftDock h5').html(options.msg);
    }

    $msgDiv.removeClass('noNotify infoNotify errorNotify alertNotify');
    if (options.type == 'error') {
        $msgDiv.addClass('errorNotify');
        $msgDiv.slideDown();
    }
    else if (options.type == 'alert') {
        $msgDiv.addClass('alertNotify');
        $msgDiv.slideDown().delay(2000).slideUp();
    }

    else if (options.type == 'info') {
        $msgDiv.addClass('infoNotify');
        $msgDiv.slideDown().delay(1000).slideUp();
    }
    else {
        $msgDiv.addClass('noNotify');
    }
}
Messenger = function () {
    this.PERSON_ADDED = 'PERSON_ADDED';
    this.PERSON_DELETED = 'PERSON_DELETED';

    var receivers = [];
    this.register = function (msgName, receiver) {
        receivers.push({ msg: msgName, receiver: receiver });
    };
    this.broadcast = function (sender, msgName, input) {
        for (var i = 0; i < receivers.length; i++) {
            var r = receivers[i];
            if (r.msg == msgName)
                r.receiver(sender, input);
        }
    };

    this.unregisterMessage = function (msgName, receiver) {

    };
};

Messenger = new Messenger();